/**
 * Created by zsgjs on 2017/2/9.
 */

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    ScrollView,
    ListView,
    Image,
    Navigator,
    TouchableOpacity,
    Animated
} from 'react-native';

import model from '../classes/Model';

var focusCellH = 30;
var seperatorH = 10;


var MHScrollView = require('../classes/MHScrollView.js');
var MHDetail = require('../classes/NewsDetail.js');

import { NativeModules } from 'react-native';
var OriginalM = NativeModules.OriginalM;

var SecModle = NativeModules.SecViewController;

var ListDemo = React.createClass({
    getDefaultProps(){
        return {
            style: {}
        }
    },

    render() {

        return (

            <Navigator
                initialRoute={{ component: MHListView}}
                configureScene={(route) => {
                    return Navigator.SceneConfigs.PushFromRight;
                }}
                renderScene={this.renderScence} />
        )
    },

    configureScene(Navigator) {
        return Navigator.SceneConfigs.FloatFromBottom;
    },

    renderScence(route, navigator){
        let Component = route.component;
        return <Component {...route.params} navigator={navigator} />
    },

    componentDidMount() {
        let bookUrl = 'https://api.douban.com/v2/book/1220562';
        // fetch("/data.json").then(function(res) {
        //     // res instanceof Response == true.
        //     if (res.ok) {
        //         res.json().then(function(data) {
        //             console.log(data.entries);
        //         });
        //     } else {
        //         console.log("Looks like the response wasn't perfect, got status", res.status);
        //     }
        // }, function(e) {
        //     console.log("Fetch failed!", e);
        // });

        fetch(bookUrl, {
            method: 'GET',
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }).then(function (response) {
            response.json().then(function (resData) {
                if (resData) {
                    console.log(resData);
                } else  {
                    console.log('resData is error');
                }
            })
        }, function (e) {
            console.log(e);
        });

        // fetch("http://www.example.org/submit.php", {
        //     method: "POST",
        //     headers: {
        //         "Content-Type": "application/x-www-form-urlencoded"
        //     },
        //     body: "firstName=Nikhil&favColor=blue&password=easytoguess"
        // }).then(function(res) {
        //     if (res.ok) {
        //         alert("Perfect! Your settings are saved.");
        //     } else if (res.status == 401) {
        //         alert("Oops! You are not authorized.");
        //     }
        // }, function(e) {
        //     alert("Error submitting form!");
        // });
        
        fetch(bookUrl, {
            
        }).then(function (res) {
            res.json().then(function (data) {
                
            })
        }) 
    }

});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },

    navStyle: {
        position:'absolute',
        left:0,
        top:0,
        height: 64,
        width:model.screen_w,
    },

    navContentStyle: {
        marginTop: 20,
        height: 44,
        width:model.screen_w,
        flexDirection:'row',
        alignItems:"center",
        justifyContent:'space-between'
    },

    leftItems: {
        marginLeft: 10,
        flexDirection:'row'
    },

    leftText:{
        color: 'darkmagenta',
        height: 20,
        fontWeight:'bold',
        backgroundColor: 'rgba(255, 255, 255, 0)'
    },

    leftImage: {
        height: 20,
        width: 20,
        backgroundColor:'darkgoldenrod',
        borderRadius: 10,
        marginLeft: 5
    },

    rightItem: {
        backgroundColor:'darkmagenta',
        height: 20,
        width: 30,
        marginRight: 10
    },

    navTitle: {
        position:'absolute',
        fontWeight: 'bold',
        fontSize:18,
        height: 44,
        width: 100,
        left: (model.screen_w - 100) * 0.5,
        top: 0,
        textAlign:"center",
        lineHeight: 44,
        backgroundColor: 'rgba(255, 255, 255, 0)'
    }
});

/*
 *   页面主列表
 */
import MyButton from '../classes/MyButton';
var number = '4008-098-101';
var MHListView = React.createClass({

    getInitialState(){
        var ds = new ListView.DataSource({rowHasChanged: (row1, row2)=>row1 !== row2});
        var trendDS = new ListView.DataSource({rowHasChanged: (row1, row2)=>row1 !== row2});
        return {
            listdata:ds.cloneWithRows(['row1','row2', 'row3','row2']),
            navBackgroundColor:'rgba(177,31,45, 0)',
            navTitleColor: 'rgba(255,255,255, 0)',
            outPutS: '点击了'
        }
    },

    render() {
        return(
            <View style={styles.container}>
                <ListView
                    style={listStyle.listViewStyle}
                    dataSource={this.state.listdata}
                    renderRow={this._renderRows}
                    renderHeader={this._renderHeader}
                    renderFooter={this._renderFooter}
                    showsVerticalScrollIndicator={false}
                    onScroll={this.listScroll}
                    onScrollAnimationEnd={this.ListScrollEnd}
                    scrollEventThrottle={100}
                >
                </ListView>
                <View style={[styles.navStyle, {backgroundColor: this.state.navBackgroundColor}]}>
                    <View style={styles.navContentStyle}>
                        <View style={styles.leftItems}>
                            <Text style={styles.leftText}>[</Text>
                            <Image style={styles.leftImage}></Image>
                        </View>
                        <TouchableOpacity activeOpacity={0.8}
                                          onPress = {this.rightItemClick}
                        >
                            <View style={styles.rightItem}></View>

                        </TouchableOpacity>
                        <Text style={[styles.navTitle, {color: this.state.navTitleColor}]}>首页</Text>

                    </View>

                </View>

            </View>

        )
    },

    rightItemClick: function () {
        OriginalM.callPhone('123456789');
        this.setState({
            navBackgroundColor:'white'
        })
    },

    _renderHeader() {
        return (<MHScrollView/>)
    },

    _renderFooter() {
        return (
            <View style={listStyle.footerStyle}>
                <View style={listStyle.lineStyle}></View>
                <Text style={listStyle.footerTitle}>24小时在线客服:</Text>
                <TouchableOpacity
                    onPress = {this.pressNum}
                >
                    <Text style={listStyle.footerPhoneNum}>{number}</Text>
                </TouchableOpacity>

                <View style={listStyle.lineStyle}></View>
            </View>
        )
    },

    _renderRows(data, secID, rowID) {
        if (rowID==0) {
            return(
                <View >
                    {this.renderFirstCell()}
                </View>
            )
        } else if (rowID == 1) {
            var myButton= {
                    width: 100,
                    height: 40,
                    marginTop: 50,
                    marginLeft: 30,
                    backgroundColor: '#aaa'
            };
            return (
                <View>
                    <View style={listStyle.secondCellStyle}>
                        <View style={listStyle.dataCell}>
                            <MyButton
                                btnTil="buttonA"
                                outPutStr={this.state.outPutS}
                                style={myButton}
                                onButtonClicked={(e)=> {

                                    this.setState({
                                        navBackgroundColor:'black',
                                        outPutS: 'liunian'
                                    })

                                    SecModle.back2prev();

                                }}
                            ></MyButton>
                        </View>
                        <View style={[listStyle.dataCell, {left: 2}]}></View>
                    </View>
                    {this.renderSeperator()}
                </View>
            )
        } else if (rowID == 2){
            return(
                <View>
                    <CommonCellHeader
                        leftTitle="视屏直播"
                        rightTitle="进入直播"
                    ></CommonCellHeader>
                    <ContentCell
                        handlePush = {this.handlePush}
                        showBottomTool={false}
                        title="波浪大师"
                        subTitle="一个用于显示文本的React组件，并且它也支持嵌套、样式，以及触摸处理。在下面的例子里，嵌套的标题和正文文字会继承来自styles.baseText的fontFamily字体样式，不过标题上还附加了它自己额外的样式。标题和文本会在顶部依次堆叠，并且被代码中内嵌的换行符分隔开。"
                    ></ContentCell>
                    {this.renderSeperator()}
                </View>
            )
        } else  {
            return(
                <View>
                    {this.renderLstCell()}
                </View>

            )
        }
    },

    renderFirstCell() {
        return(
            <View >
                <View style={listStyle.focusCellStyle}>
                    <Text style={{color: "black", fontSize: 15,  height: focusCellH, lineHeight: focusCellH, fontWeight: 'bold'}}>今日关注</Text>
                    <Text style={{color: "gray", fontSize: 14, height: focusCellH, lineHeight: focusCellH, marginLeft: 10}}>掌金官方微信：zsgjs888</Text>
                </View>
                <TrendView></TrendView>
                <View style={{backgroundColor:'gray', height: 1, width: model.screen_w, marginTop: 10}}></View>
                <View style={listStyle.serviceStyle}>
                    <View><Text style={listStyle.serviceTextStyle}>开户账户</Text></View>
                    <View><Text style={listStyle.serviceTextStyle}>vip服务</Text></View>
                    <View><Text style={listStyle.serviceTextStyle}>实盘交易</Text></View>
                </View>
                {this.renderSeperator()}
            </View>
        )
    },

    renderLstCell() {
        return(
            <View>
                <CommonCellHeader
                    leftTitle="咨询头条"
                    rightTitle="更多咨询"
                ></CommonCellHeader>
                <ContentCell
                    handlePush = {this.handlePush}
                    showBottomTool={true}
                    title="2017全球市场怎么样"
                    subTitle="指定字体的粗细。大多数字体都支持'normal'和'bold'值。并非所有字体都支持所有的数字值。如果某个值不支持，则会自动选择最接近的值。。"
                ></ContentCell>
                <ContentCell
                    handlePush = {this.handlePush}
                    showBottomTool={true}
                    title="2017全球市场怎么样"
                    subTitle="指定字体的粗细。大多数字体都支持'normal'和'bold'值。并非所有字体都支持所有的数字值。如果某个值不支持，则会自动选择最接近的值。。"
                ></ContentCell>
                <ContentCell
                    showBottomTool={true}
                    handlePush = {this.handlePush}
                    title="2017全球市场怎么样"
                    subTitle="指定字体的粗细。大多数字体都支持'normal'和'bold'值。并非所有字体都支持所有的数字值。如果某个值不支持，则会自动选择最接近的值。。"
                ></ContentCell>
            </View>
        )
    },

    renderSeperator() {
        return (
            <View style={{backgroundColor:'#ddd', height: 10, width: model.screen_w}}></View>
        )
    },

    handlePush(url) {
        const {navigator} = this.props;

        if (navigator) {
            navigator.push({
                component: MHDetail,
                params: {
                    'htmlURL': url,
                    'navTitle': '详情'
                }
            })
        }
    },

    listScroll(e) {
        var alpha = (e.nativeEvent.contentOffset.y / 64);
        if (alpha > 1) alpha = 1;
        this.setState({
            navBackgroundColor:'rgba(177, 31, 45, ' + alpha + ')',
            navTitleColor:'rgba(255, 255, 255, ' + alpha + ')'
        });
    },

    ListScrollEnd(e) {
        var alpha = (e.nativeEvent.contentOffset.y / 64);
        if (alpha > 1) alpha = 1;
        this.setState({
            navBackgroundColor:'rgba(177, 31, 45, ' + alpha + ')',
            navTitleColor:'rgba(255, 255, 255, ' + alpha + ')'
        });
    },

    pressNum(e) {
        // alert(number)
        OriginalM.callPhone('13652466686');
    }

});

/*
 *   通用头部cell
 */
var CommonCellHeader = React.createClass({
    getDefaultProps() {
        return {
            leftTitle : '',
            rightTitle : ''
        }
    },

    render() {
        return (
            <View>
                <View style={listStyle.cellHeader}>
                    <View style={listStyle.headerLeftItem}>
                        <Image style={{width: 30, height: 25, backgroundColor: 'red'}}></Image>
                        <Text style={{marginLeft : 10}}>{this.props.leftTitle}</Text>
                    </View>

                    <View style={{right: 10}}>
                        <Text style={{color: '#ddd'}}>{this.props.rightTitle}></Text>
                    </View>
                </View>
                <View style={{backgroundColor: "#ddd", width: model.screen_w, height: 1}}></View>
            </View>
        )
    }
});

/*
 *   通用内容cell
 */
var ContentCell = React.createClass({

        getDefaultProps() {
            return {
                showBottomTool: false,
                title:'',
                subTitle:''
            }
        },

        render() {
            var lines;
            var alpha;
            if (this.props.showBottomTool)
            {
                lines = 1;
                alpha= 1;
            }
            else {
                lines = 2;
                alpha= 0;
            }
            return (
                <TouchableOpacity
                    onPress = {(url)=>this.pressContentCell('http://zjwas.zsgjs.com/zj_web/a/HeadLines/detail?id=5238')}
                >
                    <View style={cellStyle.contentCellStyle}>
                        <Image style={cellStyle.cellImage}></Image>
                        <View style={cellStyle.textContent}>
                            <Text style={[cellStyle.titleStyle, cellStyle.textWith]}>{this.props.title}</Text>
                            <Text
                                style={[cellStyle.subTitleStyle, cellStyle.textWith]}
                                numberOfLines={lines}
                            >{
                                this.props.subTitle
                            }</Text>
                            <View style={[cellStyle.textWith, {height: 20, backgroundColor:'red', marginTop: 10, opacity: alpha}]}></View>
                        </View>
                    </View>
                    <View style={{backgroundColor: "#ddd", width: model.screen_w, height: 1}}></View>
                </TouchableOpacity>
            )
        },

        pressContentCell(urlStr) {
            this.props.handlePush(urlStr);
        }
    });

const cellStyle = StyleSheet.create({

    contentCellStyle: {
        backgroundColor: 'white',
        height: 100,
        flexDirection: 'row',
        alignItems:'center',
        width:model.screen_w,

    },

    cellImage: {
        height: 80,
        width: 120,
        backgroundColor: 'brown',
        marginLeft: 10,
    },

    textWith:{
        width: model.screen_w - 120 - 30,
    },

    textContent: {
        height: 80,
        marginLeft: 10,
        justifyContent:'space-around'
    },

    titleStyle: {
        color: 'black',
        fontWeight:'bold',
        fontSize: 15,
    },

    subTitleStyle: {
        marginTop: 10,
        color:'gray',
        fontSize: 13,
    }
});



const listStyle = StyleSheet.create({
    listViewStyle: {
        height: model.height - 200,
        width: model.screen_w
    },

    firstCellStyle: {
        height: focusCellH + focusCellH,
        width: model.screen_w,
        backgroundColor: 'white',
    },

    focusCellStyle: {
        width: model.screen_w - seperatorH * 2,
        height: focusCellH,
        flexDirection:'row',
        paddingLeft:20,
        alignItems:'center',
        borderRadius: 5,
        backgroundColor:'#ddd',
        marginLeft:seperatorH,
        marginTop:seperatorH
    },

    serviceStyle: {
        flexDirection:'row',
        height: 40,
        width: model.screen_w,
        alignItems:'center',
        justifyContent:"center"
    },

    serviceTextStyle: {
        color: 'black',
        fontSize:15,
        textAlign:'center',
        width: model.screen_w/3
    },

    secondCellStyle: {
        height: 100,
        flexDirection: 'row'
    },

    dataCell:{
        height:100,
        width: model.screen_w * 0.5 - 1,
        backgroundColor:'purple'
    },

    thirdStyle: {
        width: model.screen_w
    },

    cellHeader: {
        height: 40,
        flexDirection:'row',
        alignItems: 'center',
        justifyContent:'space-between'
    },

    headerLeftItem: {
        flexDirection:'row',
        alignItems:'center',
        marginLeft: 10,
    },

    footerStyle: {
        height: 40,
        width: model.screen_w,
        backgroundColor: 'aliceblue',
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },

    lineStyle: {
        height: 1,
        width:10,
        backgroundColor:'darkgray'
    },

    footerTitle: {
        color:'darkgray',
        marginLeft: 10
    },

    footerPhoneNum: {
        color:'dodgerblue',
        marginRight: 10
    }
});

/*
 *   数据趋势组件
 */
var TrendView = React.createClass({

    getInitialState(){
        var ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
        return ({
            trandData: ds.cloneWithRows(['1', 'row2' ,'row2' ,'row2','row2','row2','row2'])

        })
    },

    render() {
        return (
            <View style={trendViewStyle.contentStyle}>
                <ListView
                    dataSource={this.state.trandData}
                    renderRow={this.renderTrendRow}
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                >
                </ListView>
            </View>
        )
    },
    renderTrendRow (data) {
        return (
            <View style={trendViewStyle.cellStyle}></View>
        )
    }
});

const trendViewStyle = StyleSheet.create({

    contentStyle: {
        marginTop: 10,
        width: model.screen_w,
        height: 100,
    },

    cellStyle: {
        width: 100,
        height: 100,
        backgroundColor: 'yellow',
        marginLeft: 10
    }
});

module.exports = ListDemo;